
package Dao;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.io.InputStream;
import java.util.*;
import java.sql.*;
public class BaseDao {
    private static String driver;
    private static String url;
    private static String user;
    private static String pwd;
    Connection conn=null;
    PreparedStatement pstmt=null;
    ResultSet rs=null;
    static {
        try {
            Properties pr=new Properties();
            String co="database.properties";
            InputStream is=BaseDao.class.getClassLoader().getResourceAsStream(co);
            pr.load(is);
            driver=pr.getProperty("driver");
            url=pr.getProperty("url");
            user=pr.getProperty("user");
            pwd=pr.getProperty("pwd");
            Class.forName(driver);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    public Connection getConnection(){
        try {
            System.out.println(url);
            conn=DriverManager.getConnection(url,user,pwd);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
    public void close(){
        try {
            if(rs!=null){
                rs.close();
            }
            if(pstmt!=null){
                pstmt.close();
            }
            if(conn!=null){
                conn.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public int executeUpdate(String sql,Object[] objs){
        int count=0;
        conn=getConnection();
        try {
            pstmt=conn.prepareStatement(sql);
            for(int i=0;i<objs.length;i++){
                pstmt.setObject(i+1,objs[i]);
            }
            count=pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            close();
        }
        return count;
    }
    public ResultSet executeQuery(String sql,Object...objects){

        ResultSet rs=null;
        conn=getConnection();
        try {
            pstmt=conn.prepareStatement(sql);
            for(int i=0;i<objects.length;i++){
                pstmt.setObject(i+1,objects[i]);
            }
            rs=pstmt.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rs;
    }
   /* public  static void main(String[] args) {
        BaseDao baseDao = new BaseDao();
        System.out.println(baseDao.getConnection());
    }*/
}
